package controllers

import (
	"bytes"
	"net"
	"os"
	"os/exec"
	"regexp"
	"runtime"
	"strings"

	"github.com/go-resty/resty/v2"
	"github.com/iris-contrib/middleware/cors"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/mvc"
	"github.com/mlogclub/simple/web"
	"github.com/sirupsen/logrus"

	"bbs-go/controllers/api"
)

func GetLocalMac() (mac string) {
	// 获取本机的MAC地址
	interfaces, err := net.Interfaces()
	if err != nil {
		panic("Poor soul, here is what you got: " + err.Error())
	}
	var rs string = ""
	for _, inter := range interfaces {
		logrus.Info(inter.Name)
		mac := inter.HardwareAddr //获取本机MAC地址
		if mac != nil {
			logrus.Info("MAC =====111 ", mac)
			rs = mac.String()
		}
	}
	logrus.Info("MAC = ", rs)
	return rs
}

func GetSerialNumber() string {
	sysType := runtime.GOOS
	if sysType == "darwin" {
		// MacPro系统
		return getDarwinSerialNumber()
	}
	if sysType == "linux" {
		// LINUX系统
		return GetLinuxSerialNumber()
	}
	if sysType == "windows" {
		// windows系统
		return GetWindowsSerialNumber()
	}
	return ""
}

func GetWindowsSerialNumber() string {
	cmd := exec.Command("wmic", "baseboard", "get", "serialnumber") // Windows平台上使用WMIC命令获取主板序列号
	output, err := cmd.Output()
	if err != nil {
		return ""
	}
	// 从输出中提取主板序列号信息
	lines := strings.Split(string(output), "\n")
	for _, line := range lines[1:] {
		fields := strings.Fields(line)
		if len(fields) > 0 {
			return fields[0]
		}
	}

	return ""
}

func getDarwinSerialNumber() string {
	cmd := exec.Command("system_profiler", "SPHardwareDataType")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		return ""
	}
	re := regexp.MustCompile(`Serial Number (.+)`)
	matches := re.FindSubmatch(out.Bytes())
	if len(matches) < 2 {
		return ""
	}
	if strings.Contains(string(matches[0]), ":") {
		return strings.Trim(strings.Split(string(matches[0]), ":")[1], "")
	}

	return string(matches[0])
}

func GetLinuxSerialNumber() string {
	cmd := exec.Command("dmidecode", "-s", "system-serial-number") // dmidecode命令用于读取系统信息
	output, err := cmd.Output()
	if err != nil {
		return ""
	}
	// 去除输出结果前后的空格并返回
	return strings.TrimSpace(string(output))
}

func Router() {
	app := iris.New()
	app.Logger().SetLevel("warn")
	app.Use(recover.New())
	app.Use(logger.New())
	app.Use(cors.New(cors.Options{
		AllowedOrigins:   []string{"*"}, // allows everything, use that to change the hosts.
		AllowCredentials: true,
		MaxAge:           600,
		AllowedMethods:   []string{iris.MethodGet, iris.MethodPost, iris.MethodOptions, iris.MethodHead, iris.MethodDelete, iris.MethodPut},
		AllowedHeaders:   []string{"*"},
	}))
	app.AllowMethods(iris.MethodOptions)

	app.OnAnyErrorCode(func(ctx iris.Context) {
		path := ctx.Path()
		var err error
		if strings.Contains(path, "/api/admin/") {
			err = ctx.JSON(web.JsonErrorCode(ctx.GetStatusCode(), "Http error"))
		}
		if err != nil {
			logrus.Error(err)
		}
	})

	app.Any("/", func(i iris.Context) {
		sysType := runtime.GOOS
		var html string
		html += "<h1>系统: " + sysType + "</h1>"
		html += "<h1>MAC地址: " + GetLocalMac() + "</h1>"
		html += "<h1>主板序列号: " + GetSerialNumber() + "</h1>"
		_, _ = i.HTML(html)
	})

	// api
	mvc.Configure(app.Party("/api"), func(m *mvc.Application) {
		m.Party("/sign").Handle(new(api.SignController))
	})

	app.Get("/api/img/proxy", func(i iris.Context) {
		url := i.FormValue("url")
		resp, err := resty.New().R().Get(url)
		i.Header("Content-Type", "image/jpg")
		if err == nil {
			_, _ = i.Write(resp.Body())
		} else {
			logrus.Error(err)
		}
	})

	if err := app.Listen(":8082",
		iris.WithConfiguration(iris.Configuration{
			DisableStartupLog:                 false,
			DisableInterruptHandler:           false,
			DisablePathCorrection:             false,
			EnablePathEscape:                  false,
			FireMethodNotAllowed:              false,
			DisableBodyConsumptionOnUnmarshal: false,
			DisableAutoFireStatusCode:         false,
			EnableOptimizations:               true,
			TimeFormat:                        "2006-01-02 15:04:05",
			Charset:                           "UTF-8",
		}),
	); err != nil {
		logrus.Error(err)
		os.Exit(-1)
	}
}
